<?php
header("Content-Type: text/html;charset=utf-8");
defined('InNcPHP') or exit('Access Invalid!');

class memberControl extends SystemControl{

	private $links = array(
		array('url'=>'act=member&op=index','lang'=>'nc_manage'),
        //array('url'=>'act=member&op=merchant_edit','lang'=>'nc_edit')
	);
	public function __construct(){
		parent::__construct();
		Language::read('member');
	}

    /**
     * 主页
     */
	public function indexOp(){
	    /* @var memberModel $model */
		$model = Model('member');

		//查询条件
        $condition=array();
        if (!empty($_GET['search_nickname'])){
            $condition['mobile'] = array('like','%'.$_GET['search_nickname'].'%');
        }
        $time_from = strtotime($_GET['search_stime']);
        $time_to = strtotime($_GET['search_etime']);
        if ($time_from && $time_to) {
            $time_to = $time_to + 86400;
            $condition['add_time'] = array('between',array($time_from,$time_to));
        } elseif ($time_from) {
            $condition['add_time'] = array('egt',$time_from);
        } elseif ($time_to) {
            $time_to = $time_to + 86400;
            $condition['add_time'] = array('elt',$time_to);
        }

        Tpl::output('search', $_GET);

		$list = $model->getMemberListPage($condition, '*', 10);
		Tpl::output('member_list',$list);
        Tpl::output('member_sex',$model::$member_sex);
		Tpl::output('page',$model->showpage());
		Tpl::output('top_link',$this->sublink($this->links, 'index'));
		Tpl::showpage('member.index');
	}

    /**
     * 商家列表
     */
	public function merchantOp()
    {
        /** @var member_merchantModel $model */
        $model = Model('member_merchant');

        //查询条件
        $condition=array();
        if (!empty($_GET['search_shop_name'])){
            $condition['mc_shop_name'] = array('like','%'.$_GET['search_shop_name'].'%');
        }
        $time_from = strtotime($_GET['search_stime']);
        $time_to = strtotime($_GET['search_etime']);
        if ($time_from && $time_to) {
            $condition['mc_apply_time'] = array('between',array($time_from,$time_to));
        } elseif ($time_from) {
            $condition['mc_apply_time'] = array('egt',$time_from);
        } elseif ($time_to) {
            $condition['mc_apply_time'] = array('elt',$time_to);
        }

        $list = $model->getMerchantListPage($condition, '*', 10);
        foreach ($list as $k => $v) {
            $list[$k]['mc_lic_img'] = UPLOAD.'product/'.$v['mc_lic_img'];
            $list[$k]['mc_idcard_img'] = UPLOAD.'product/'.$v['mc_idcard_img'];
            $list[$k]['mc_idcardb_img'] = UPLOAD.'product/'.$v['mc_idcardb_img'];
        }

        Tpl::output('search', $_GET);
        Tpl::output('merchant_list',$list);
        Tpl::output('page',$model->showpage());
        Tpl::output('state',$model->state);
        Tpl::output('bank_state',$model->bank_state);
        Tpl::showpage('merchant.index');
        Tpl::output('top_link',$this->sublink(array(
            array('url'=>'act=member&op=merchant','lang'=>'nc_manage'),
        ), 'merchant'));
    }

    /**
     * 审核
     */
    public function merchant_checkOp()
    {
        /** @var member_merchantModel $model */
        $model = Model('member_merchant');
        /** @var memberModel $merber_model */
        $merber_model = Model('member');

        $mid = intval($_POST['mid']);
        $state = intval($_POST['state']);
        if ($state === 1) {
            $res = $model->updateMerchant(array('merchant_id'=>$mid), array('mc_status'=>1));
            if ($res) {
                $res = $merber_model->updateMember(array('member_id'=>$mid), array('is_merchant'=>1));
                $res && exit(json_encode(array('errcode'=>0)));
            }
        } elseif ($state === 2) {
            $res = $model->updateMerchant(array('merchant_id'=>$mid), array('mc_status'=>2));
            $res && exit(json_encode(array('errcode'=>0)));
        }
        exit(json_encode(array('errcode'=>4000)));
    }

    /**
     * 商家编辑
     */
    public function merchant_editOp(){
        $model = Model('member_merchant');
        $class_model = Model('class');
        $business_info_model = Model('business_info');
        $merchant_id = intval($_GET['merchant_id']);
        $merchant_info = $model->getMerchantInfo(array('merchant_id'=>$merchant_id));
        $bank_name= $business_info_model->getBank_info(array('bank_code'=>$merchant_info['bank_no']),'bank_name');
        $merchant_info['bank_no'] = $bank_name['bank_name'];

        if(chksubmit()){

            $business_code = $business_info_model->getBusinessInfo(array('business_type'=>$_POST['business_type'],'one_class'=>$_POST['one_class'],'tow_class'=>$_POST['tow_class'],'three_class'=>$_POST['three_class']),'business_code');
            $bank_code = $business_info_model->getBank_info(array('bank_name'=>$_POST['bank_no']),'bank_code');
            if(empty($bank_code)){
                showMessage('卡户支行不匹配');
            }

            $param = array();
            $param['mc_shop_name'] = $_POST['mc_shop_name'];
            $param['mch_shortname'] = $_POST['mch_shortname'];
            $param['mc_name'] = $_POST['mc_name'];
            $param['mc_phone'] = $_POST['mc_phone'];
            $param['mc_cate_name'] = $_POST['mc_cate_name'];
            $param['email'] = $_POST['email'];
            $param['province'] = $_POST['province'];
            $param['city'] = $_POST['city'];
            $param['address'] = $_POST['address'];
            $param['service_phone'] = $_POST['service_phone'];
            $param['balance_account'] = $_POST['balance_account'];
            $param['balance_name'] = $_POST['balance_name'];
            $param['bank_no'] = $bank_code['bank_code'];//支行联行号
            $param['industry_no'] = $business_code['business_code'];//行业类别编号
            $param['id_card_no'] = $_POST['id_card_no'];
            $param['payment_type3'] = $_POST['payment_type3'];
            $param['payment_type8'] = $_POST['payment_type8'];
            $param['payment_type7'] = $_POST['payment_type7'];
            $param['license_num'] = $_POST['license_num'];
            $param['license_start_date'] = $_POST['license_start_date'];
            $param['license_period'] = 1;
            $param['license_end_date'] = $_POST['license_end_date'];
            $param['license_scope'] = $_POST['license_scope'];
            $param['district']  = $_POST['district'];
            $param['balance_type'] = $_POST['balance_type'];

            //如果营业执照有重新上传的话
            if ($_FILES['mc_lic_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_lic_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_lic_img'] = $upload->getSysSetPath() . $upload->file_name;

                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果身份证正面照片有重新上传的话
            if ($_FILES['mc_idcard_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_idcard_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_idcard_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果身份证反面照片有重新上传的话
            if ($_FILES['mc_idcardb_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_idcardb_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_idcardb_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }

            $res = $model->updateMerchant(array('merchant_id'=>$merchant_id),$param);//信息写入数据库
            $imgs = array(
                'mc_lic_img'=>isset($param['mc_lic_img'])?$param['mc_lic_img']:$merchant_info['mc_lic_img'],
                'mc_idcard_img'=>isset($param['mc_idcard_img'])?$param['mc_idcard_img']:$merchant_info['mc_idcard_img'],
                'mc_idcardb_img'=>isset($param['mc_idcardb_img'])?$param['mc_idcardb_img']:$merchant_info['mc_idcardb_img'],
            );
            $datas = $this->pay_parameterOp($param,$imgs);
            if($datas['status'] =='900'){
                //进件成功,将返回的子商户ID写入数据库
                $model->updateMerchant(array('merchant_id'=>$merchant_id),array('submch_id'=>$datas['data'],'bank_status'=>10));
                showMessage('进件成功,请等待银行审核', 'index.php?act=member&op=merchant');
            }else{
                showDialog($datas['info']);
            }

        }

        $merchant_info['mc_lic_img'] = UPLOAD . 'product/' .$merchant_info['mc_lic_img'];//商家营业执照
        $merchant_info['mc_idcard_img'] = UPLOAD . 'product/' .$merchant_info['mc_idcard_img'];//身份证正面照片
        $merchant_info['mc_idcardb_img'] = UPLOAD.'product/'.$merchant_info['mc_idcardb_img'];//反面照
        $industry = $class_model->getclassList(array('parent_id'=>0));//获取行业类别一级编号
        Tpl::output('industry',$industry);
        Tpl::output('merchant_info',$merchant_info);
        Tpl::output('top_link', $this->sublink($this->links, 'edit'));
        Tpl::showpage('merchant_edit');


    }

    /**
     * 获取子级的地区
     */
    public function getAreaChildOp(){
        $parent_id = $_GET['parent_id'];
        /* @var areaModel $area_model */
        $area_model = Model('class');
        $areaList = $area_model->getclassList(array('parent_id'=>$parent_id));
        die(json_encode($areaList));
    }

    /**
     * 接商户进件
     */
    public function  pay_parameterOp($param,$imgs){
        require_once BASE_DATA_PATH.'/vendors/yfpay/yifuenter.php';
        $yifuenter = new yifuenter();
        $parameter = array();
        $parameter['mch_name'] = $param['mc_shop_name'];
        $parameter['mch_shortname'] = $param['mch_shortname'];
        $parameter['province'] = $param['province'];
        $parameter['city'] = $param['city'];
        $parameter['address'] = $param['address'];
        $parameter['mobile'] = $param['mc_phone'];
        $parameter['email'] = $param['email'];
        $parameter['service_phone'] = $param['service_phone'];
        $parameter['bank_no']  = $param['bank_no'];
        $parameter['industry_no'] = $param['industry_no'];
        $parameter['balance_name'] = $param['balance_name'];
        $parameter['balance_account']  = $param['balance_account'];
        $parameter['id_card_no']  = $param['id_card_no'];
        $parameter['contact']  = $param['mc_name'];
        $parameter['payment_type3']  = $param['payment_type3'];
        $parameter['payment_type7']  = $param['payment_type7'];
        $parameter['payment_type8'] = $param['payment_type8'];
        $parameter['license_num'] = $param['license_num'];
        $parameter['license_start_date'] = $param['license_start_date'];
        $parameter['license_period'] = $param['license_period'];
        $parameter['license_end_date'] = $param['license_end_date'];
        $parameter['license_scope'] = $param['license_scope'];
        $parameter['orgno'] = $yifuenter::ORGNO;
        $parameter['district'] = $param['district'];
        $parameter['secondtimestamp'] = time();
        $parameter['nonce_str'] =rand(10000000,99999999);

        $parameter['tag'] = 324;
        $parameter['balance_type'] = $param['balance_type'];
        //生成签名
        $stringA=$yifuenter->getSignContent($parameter);
        $stringSignTemp = $stringA.'&key='.$yifuenter::KEY;
        $sign = strtoupper(md5($stringSignTemp));

        //需要提交的数据
        $parameter['sign'] = $sign;
        $parameter['id_card_img_f'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$imgs['mc_idcard_img'];
        $parameter['id_card_img_b'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$imgs['mc_idcardb_img'];
        $parameter['license_img'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$imgs['mc_lic_img'];
        $submiturl = 'https://api.efujr.com:8118/agentmng/mchinlet';//宜富进件接口
        //$submiturl = 'https://apitest.efujr.com:8443/agentmng/mchinlet';//宜富测试接口
        $http_url = 'https://admin.hoocen.com';


        $res = $yifuenter->curl_form($parameter,$submiturl,$http_url);
        return json_decode($res,true);
        //var_dump($res);exit;
        //return $res;



    }


    /**
     * 进件编辑接口
     */
    public  function edit_parameterOp(){
        require_once BASE_DATA_PATH.'/vendors/yfpay/yifuenter.php';
        $yifuenter = new yifuenter();
        $model = Model('member_merchant');
        $business_info_model = Model('business_info');
        $merchant_id = intval($_GET['merchant_id']);
        $class_model = Model('class');
        $merchant_info = $model->getMerchantInfo(array('merchant_id'=>$merchant_id));
        if(empty($merchant_info['submch_id'])){
            showMessage('该商户还未进件');
        }
        if(chksubmit()){
            $sign_arr = $this->getparameter($_POST);

            if($_POST['bank_no']){
                $bank_code = $business_info_model->getBank_info(array('bank_name'=>$_POST['bank_no']),'bank_code');
                $sign_arr['bank_no'] = $bank_code['bank_code'];
            }
            if(!empty($_POST['business_type']) && !empty($_POST['one_class']) && !empty($_POST['tow_class']) && !empty($_POST['three_class'])){
                $business_code = $business_info_model->getBusinessInfo(array('business_type'=>$_POST['business_type'],'one_class'=>$_POST['one_class'],'tow_class'=>$_POST['tow_class'],'three_class'=>$_POST['three_class']),'business_code');
                $sign_arr['bank_no'] = $business_code['business_code'];
            }

            //如果营业执照有重新上传的话
            if ($_FILES['mc_lic_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_lic_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_lic_img'] = $upload->getSysSetPath() . $upload->file_name;

                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果身份证正面照片有重新上传的话
            if ($_FILES['mc_idcard_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_idcard_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_idcard_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果身份证反面照片有重新上传的话
            if ($_FILES['mc_idcardb_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('mc_idcardb_img');
                if($result){
                    //得到图片上传后的路径
                    $param['mc_idcardb_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$merchant_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }


            //编辑进件操作
            $sign_arr['uid'] = $merchant_info['submch_id'];
            $sign_arr['orgno'] = $yifuenter::ORGNO;
            $sign_arr['secondtimestamp'] = time();
            $sign_arr['nonce_str']  = rand(10000000,99999999);
            $sign_arr['tag'] =324;
            $stringA=$yifuenter->getSignContent($sign_arr);
            $stringSignTemp = $stringA.'&key='.$yifuenter::KEY;
            $sign = strtoupper(md5($stringSignTemp));
            $sign_arr['sign'] = $sign;
            if(isset($param['mc_lic_img'])){
                $sign_arr['license_img'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$param['mc_lic_img'];
            }
            if(isset($param['mc_idcard_img'])){
                $sign_arr['id_card_img_f'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$param['mc_idcard_img'];
            }
            if(isset($param['mc_idcardb_img'])){
                $sign_arr['id_card_img_b'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$param['mc_idcardb_img'];
            }
            $submiturl = 'https://api.efujr.com:8118/agentmng/updatemchinlet';//正式环境接口
            //$submiturl = 'https://apitest.efujr.com:8443/agentmng/updatemchinlet';//测试接口
            $http_url = 'https://admin.hoocen.com';

            $res = $yifuenter->curl_form($sign_arr,$submiturl,$http_url);
            $data = json_decode($res,true);
           if($data['status'] =='900'){
                showMessage('进件编辑成功,请等待重新银行审核', 'index.php?act=member&op=merchant');
            }else{
                showDialog($data['info']);
            }

        }
        /*$parameter = array();
        $parameter['uid'] = '100003378690';
        $parameter['orgno'] = $yifuenter::ORGNO;
        $parameter['secondtimestamp'] = time();
        $parameter['nonce_str'] =rand(10000000,99999999);
        $parameter['tag'] = 324;
        $stringA=$yifuenter->getSignContent($parameter);
        $stringSignTemp = $stringA.'&key='.$yifuenter::KEY;
        $sign = strtoupper(md5($stringSignTemp));
        $parameter['sign'] = $sign;
        $parameter['license_img'] = '@'.BASE_DATA_PATH.'/'.'upload/'.'product/'.$merchant_info['mc_lic_img'];
        $submiturl = 'https://api.efujr.com:8118//agentmng/updatemchinlet';
        $http_url = 'https://admin.hoocen.com';

        $res = $yifuenter->curl_form($parameter,$submiturl,$http_url);
        var_dump($res);exit;*/
        $merchant_info['mc_lic_img'] = UPLOAD . 'product/' .$merchant_info['mc_lic_img'];//商家营业执照
        $merchant_info['mc_idcard_img'] = UPLOAD . 'product/' .$merchant_info['mc_idcard_img'];//身份证正面照片
        $merchant_info['mc_idcardb_img'] = UPLOAD.'product/'.$merchant_info['mc_idcardb_img'];//反面照
        $industry = $class_model->getclassList(array('parent_id'=>0));//获取行业类别一级编号
        Tpl::output('industry',$industry);
        Tpl::output('merchant_info',$merchant_info);
        Tpl::output('top_link', $this->sublink($this->links, 'edit'));
        Tpl::showpage('merchant_parameter_edit');



    }

    private function post_image($path){
        $obj = new CurlFile($path);
        $obj->setMimeType("application/octet-stream");//必须指定文件类型，否则会默认为application/octet-stream，二进制流文件</span>
       return $obj;
    }


    private function cul_file_create($filename,$mimetype='',$postname=''){
        return '@'.$filename.';type='.$mimetype.';filename='.$postname;
    }

    public function getparameter($parameter){
        $sign_arr = array();
        foreach ($parameter as $key => $value) {
            if ($key == 'form_submit' || $key == 'bank_no' || $value == '' || $key =='business_type' || $key =='business_type' || $key=='one_class' || $key =='tow_class' || $key =='three_class') {
                continue;
            }
            $sign_arr[$key] = $value;
        }
        return $sign_arr;
    }


    public function ajaxOp(){

        $business_info_model = Model('business_info');
        $bank_code = $business_info_model->getBank_info(array('bank_name'=>$_GET['bank_no']),'bank_code');
        if(empty($bank_code)){
            exit('false');
        }else{
            exit('true');
        }

    }

    public function ajax_bank_nameOp()
    {
        $business_info_model = Model('business_info');
        $condition = array();
        $condition['bank_name'] = array('like', '%' . trim($_POST['name']) . '%');
        $bank_code = $business_info_model->getBank_info_name($condition,'bank_name');
        if($bank_code){
            echo json_encode(array('data'=>$bank_code,'result'=>1));exit;
        }else{
            output_error(array('result'=>0,'data'=>''));exit;
        }

    }

    //商家状态
    public function merchant_stateOp()
    {
        $mid = intval($_POST['mid']);
        $type = intval($_POST['type']);
        if($type==1){
            if($mid>0){
                //所有商品进行下架处理
                $model = Model('ticket');
                $res = $model->updateTicket(array('merchant_id'=>$mid),array('tk_status'=>0));
                $re = Model('member_merchant')->updateMerchant(array('merchant_id'=>$mid),array('is_disable'=>1));
                $re && exit(json_encode(array('errcode'=>0)));
            }
        }elseif($type==2){
            //启用
            if($mid>0){
                $re = Model('member_merchant')->updateMerchant(array('merchant_id'=>$mid),array('is_disable'=>0));
                $re && exit(json_encode(array('errcode'=>0)));
            }
        }

        exit(json_encode(array('errcode'=>4000)));
    }



}
